package top.went.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.went.exception.ServiceException;
import top.went.pojo.CustomerEntity;
import top.went.service.CustomerExcelInputService;
import top.went.service.CustomerService;
import top.went.service.FileService;
import top.went.vo.Code;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.rmi.ServerException;
import java.util.*;

@Controller
@ResponseBody
public class FileUploadController {

    @Autowired
    private FileService fileService;
    @Autowired
    private CustomerExcelInputService customerExcelInputService;
    @Autowired
    private CustomerService customerService;

    @RequestMapping("/file_upload")
    @ResponseBody
    public Map upload(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        try {
            Map<String, Object> json = new HashMap<String, Object>();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = null;
            Map map = multipartRequest.getFileMap();
            for (Iterator i = map.keySet().iterator(); i.hasNext(); ) {
                Object obj = i.next();
                file = (MultipartFile) map.get(obj);
            }

            String path = request.getSession().getServletContext().getRealPath("WEB-INF\\img");

            String targetFileName = fileService.upload(file, path);
            //拼url
            String url = targetFileName;
            Map fileMap = new HashMap();

            fileMap.put("uri", targetFileName);
            fileMap.put("url", path);
            System.out.println(targetFileName + "         bibibibi          " + path);
            return fileMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @RequestMapping("/excel_upload")
    @ResponseBody
    public Code excelUpload(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        try {
            Map<String, Object> json = new HashMap<String, Object>();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = null;
            Map map = multipartRequest.getFileMap();
            for (Iterator i = map.keySet().iterator(); i.hasNext(); ) {
                Object obj = i.next();
                file = (MultipartFile) map.get(obj);
            }
            String path = request.getSession().getServletContext().getRealPath("WEB-INF\\excel");
            Code code = fileService.excelupload(file, path);
            return code;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 多文件上传
     * @param request
     * @param response
     * @param id
     * @return
     * @throws ServiceException
     */
    @RequestMapping("/files_upload")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request, HttpServletResponse response, Integer id) throws ServiceException {
        try {
            List<String> list = new ArrayList<String>();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = null;
            Map map = multipartRequest.getFileMap();
            for (Iterator i = map.keySet().iterator(); i.hasNext(); ) {
                Object obj = i.next();
                file = (MultipartFile) map.get(obj);
            }

            String path = request.getSession().getServletContext().getRealPath("upload");
            String fileName = fileService.uploadfiles(file, path);
            System.out.println(fileName);
            //todo
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param request
     * @param response
     * @param filename
     * @return
     * @throws Exception
     */
    @RequestMapping(value="files_download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response,
                                           @RequestParam("filename") String filename)throws Exception {

        //下载文件路径
        String path = request.getServletContext().getRealPath("upload");
        File file = new File(path + File.separator + filename);
        System.out.println(path + File.separator + filename);

        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes("gbk"),"iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
//        response.addHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("gbk"),"iso-8859-1"));

        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        System.out.println(FileUtils.readFileToByteArray(file)+"            zxcasdasd");
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}

